package com.tul.exercise.base.thread.base;

/**
 * join()方法使用
 */
public class Joining {
    public static void main(String[] args) {
        Sleeper sleeper = new Sleeper("Sleepy", 1500);
        Sleeper grumpy = new Sleeper("Grumpy", 1500);

        // dopey 等待 sleeper完成后，才完成
        Joiner dopey = new Joiner("Dopery", sleeper);

        // doc 等待 grumpy完成后，才完成
        Joiner doc = new Joiner("Doc", grumpy);


        // 输出
        /*Sleepy 任务完成
        Sleepy has awakened
        Dopery join completed
        Dopery 任务完成
        Grumpy 任务完成
        Grumpy has awakened
        Doc join completed
        Doc 任务完成*/

    }
}

/**
 * 休眠线程
 */
class Sleeper extends Thread {
    // 休眠时间
    private int duration;

    public Sleeper(String name, int sleepTime) {
        super(name);
        duration = sleepTime;
        start();
    }
    // 任务
    public void run() {
        try {
            sleep(duration);
            System.out.println(getName() + " 任务完成");
        } catch (InterruptedException e) {
            System.out.println(getName() + "was interrrupted. " + "isInterrupted :" + isInterrupted());
        }

        System.out.println(getName() + " has awakened");
    }
}

/**
 * join的线程
 */
class Joiner extends Thread {
    private Sleeper sleeper;

    public Joiner(String name, Sleeper sleeper) {
        super(name);
        this.sleeper = sleeper;
        start();
    }

    public  void run() {

        try{
            // 等待sleeper 任务完成
            sleeper.join();

        } catch (InterruptedException e) {
            System.out.println("Interrupted");
        }

        System.out.println(getName() + " join completed");
        System.out.println(getName() + " 任务完成");

    }
}
